package dbcontent

import (
	"fmt"
	"gitee.com/ichub/gofactroy/config"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)

var DB *gorm.DB

func InitDB_Config() (*gorm.DB, *config.Config) {
	cfg := config.Ini()
	dbinst, err := gorm.Open(cfg.Datasource.DriverName,
		fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&mb4&parseTime=True&loc=Local",
			cfg.Datasource.Username, cfg.Datasource.Password,
			cfg.Datasource.Host, cfg.Datasource.Port, cfg.Datasource.Database))

	if err != nil {
		panic("failed to connect database,err:" + err.Error())
	}

	DB = dbinst
	return dbinst, cfg
}

func InitDB() *gorm.DB {
	dbinst, err := gorm.Open("mysql",
		"attend:123456@tcp(120.78.136.63:3306)/cms?charset=utf8&mb4&parseTime=True&loc=Local")
	if err != nil {
		panic("failed to connect database,err:" + err.Error())
	}

	DB = dbinst
	return dbinst
}
func InitDB_mysql(conn string) *gorm.DB {
	fmt.Println(conn)
	dbinst, err := gorm.Open("mysql", conn)
	if err != nil {
		panic("Failed to connect database, err:" + err.Error())
	}

	DB = dbinst
	return dbinst
}

func InitDB_pg(conn string) *gorm.DB {
	var (
		err    error
		dbinst *gorm.DB
		//config = common.G_AppConfig
		//url = config.DBPostgres.DBUrl()
	)
	dbinst, err = gorm.Open("postgres", conn)
	if err != nil {
		fmt.Println("连接pg失败")
		panic(err.Error())
	}
	if err = dbinst.DB().Ping(); err != nil {

	}
	//dbinst.AutoMigrate(&cmsmodel.CmsColumn{})
	dbinst.DB().SetMaxIdleConns(50)
	dbinst.DB().SetMaxOpenConns(50)
	dbinst.DB().SetConnMaxLifetime(7200)
	DB = dbinst
	return dbinst
}

/**
dbcontent url
*/
func postgresDBUrl() string {
	return fmt.Sprintf("host=%s port=%d shop-test=%s dbname=%s password=%s sslmode=disable",
		"192.168.1.53", 54321, "postgres", "cms", "password")
}

/**
Init gorm 配置初始化 数据库连接
*/
func InitDB_postgres() *gorm.DB {
	return InitDB_pg(postgresDBUrl())

}

func GetDB() *gorm.DB {
	//return db.GetDB()
	return DB
}

var TestMysqlDBUrl = func() string {
	return fmt.Sprintf("attend:123456@tcp(attend.akunlong.top:3306)/%s?charset=utf8&mb4&parseTime=True&loc=Local", "cms")
}

var TestPgDBUrl = func() string {
	return fmt.Sprintf("host=%s port=%d shop-test=%s dbname=%s password=%s sslmode=disable",
		"192.168.4.119", 5432, "postgres", "cms", "123456")

}

var TestRoachPgDBUrl = func() string {
	return fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s sslmode=require",
		"192.168.13.235", 26257, "test", "cms", "123456")
	//return "postgresql://root@192.168.4.119:26257/cms?sslmode=disable"

}

var TestMyRoachDBUrl = func() string {

	return "postgresql://root@192.168.4.119:26257/cms?sslmode=disable"

}
